using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using backend.Data;
using backend.Models;
using backend.Models.Dtos;
using Microsoft.EntityFrameworkCore;

namespace backend.Repositories
{
    public class FailureRepo : BaseRepo<CampusFacilityRepairManagementDbContext, Failure>
    {
        private readonly IMapper _mapper;
        private readonly CampusFacilityRepairManagementDbContext _context;

        public FailureRepo(CampusFacilityRepairManagementDbContext context, IMapper mapper) : base(context)
        {
            _mapper = mapper;
            _context = context;
        }

        public async Task<Failure> CreateFailureAsync(string fid, string failureName, string professionID)
        {
            // Check if there's an existing entry with the same name but marked as stopped using.
            var existingFailure = await DbSet.FirstOrDefaultAsync(f => f.FName == failureName && f.FStopUsing);

            if (existingFailure != null)
            {
                // If found, reactivate it by setting FStopUsing to false.
                existingFailure.FStopUsing = false;
                await SaveChangesAsync();
                return existingFailure;
            }
            else
            {
                // Otherwise, add the new entry.
                var failure = new Failure { FId = fid, FName = failureName, FStopUsing = false, PId = professionID };
                await DbSet.AddAsync(failure);
                await SaveChangesAsync();
                return failure;
            }
        }

        public async Task<bool> DeleteFailureAsync(string fId)
        {
            var failure = await DbSet.FindAsync(fId);
            if (failure != null)
            {
                // Instead of removing the entity, mark it as not in use.
                failure.FStopUsing = true;
                await SaveChangesAsync();
                return true;
            }
            return false;
        }

        public async Task<List<FailureDto>> GetFailuresAsync()
        {
            var failures = await DbSet
                .Where(f => !f.FStopUsing)
                .ToListAsync();

            var failureDtos = failures.Select(failure => new FailureDto
            {
                Value = failure.FId,
                Label = failure.FName,
                IsStopUsing = failure.FStopUsing,
            }).ToList();

            return failureDtos;
        }

        public async Task SaveChangesAsync()
        {
            await _context.SaveChangesAsync();
        }
    }
}